/**
 * Created by zhanglihe on 15/11/7.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'datepicker'
], function ($, common, ready, Collection, template, Model, dialog, datepicker) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            //loading();
            this.fetch();
            this.event();
        },
        fetch: function () {
            var html = template('add-tpl');
            $("#main-view").html(html);
        },
        event: function () {
            this.data = {};
            var _this = this;
            //日期
            $('.long_date').on('click', function () {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd HH:mm:ss'
                });
            });
            $("#btn-search").on("click", function (e) {
                e.preventDefault();
                _this.select_goods(e);
            });
            //保存
            $("#btn_save").on("click", function () {

                _this.data.image = $.trim($("input[name='image']").val());
                _this.data.share_content = $.trim($("textarea[name='share_content']").val());
                if (_this.data.image == '') {
                    Alert({msg: '请上传图片', type: 'error'});
                    return false;
                }

                if ($("input[name='start_num']").size() == 0 && $("input[name='start_num1']").size() == 0) {
                    Alert({msg: '团购规则不能为空', type: 'error'});
                    return false;
                }
                if ($("input[name='sku_id']").size() == 0) {
                    var price_config = new Array();

                    $("input[name='start_num']").each(function (i) {
                        var start_num = $.trim($(this).val());
                        var price = $.trim($("input[name='price']").eq(i).val());
                        var commission = $.trim($("input[name='commission']").eq(i).val());
                        if (start_num == '' || start_num < 1) {
                            Alert({msg: '请输入正确的人数', type: 'error'});
                            return false;
                        }
                        if (price == '' || price < 0.01) {
                            Alert({msg: '请输入正确的价格', type: 'error'});
                            return false;
                        }
                        if (commission < 0) {
                            Alert({msg: '请输入正确的佣金', type: 'error'});
                            return false;
                        }
                        var item = new Array();
                        item['start_num'] = start_num;
                        item['price'] = price;
                        item['commission'] = commission;
                        price_config.push(item);
                    });
                    console.log(price_config);
                    var price_config_len = price_config.length;
                    _this.data.price_config = new Array();
                    if (price_config_len < 1) {
                        Alert({msg: '请输入正确的规则', type: 'error'});
                        return false;
                    }
                    for (var i = 0; i < price_config_len; i++) {
                        var start_num = price_config[i].start_num;
                        var price = price_config[i].price;
                        var commission = price_config[i].commission;
                        _this.data.price_config.push(start_num + ',' + price + ',' + commission);
                    }
                } else {
                    var price_config = new Array();

                    $("input[name='sku_id']:checked").each(function (i) {
                        var sku_id = $.trim($(this).val());

                        var price = $.trim($("input[name='price_1_" + sku_id + "']").val());
                        var start_num = $.trim($("input[name='start_num1']").val());
                        var commission = $.trim($("input[name='commission1']").val());

                        if (start_num == '' || start_num < 1) {
                            Alert({msg: '请输入正确的人数', type: 'error'});
                            price_config = new Array();
                            return false;
                        }
                        if (price == '' || price < 0.01) {
                            Alert({msg: '请输入正确的价格', type: 'error'});
                            price_config = new Array();
                            return false;
                        }
                        if (commission < 0) {
                            Alert({msg: '请输入正确的佣金', type: 'error'});
                            return false;
                        }
                        var item = new Array();
                        item['start_num'] = start_num;
                        item['sku_id'] = sku_id;
                        item['price'] = price;
                        item['commission'] = commission;
                        price_config.push(item);

                        //查看是否有第二组价格
                        if ($('[name="start_num2"]').attr('data-is-del') != 1) {
                            var price = $.trim($("input[name='price_2_" + sku_id + "']").val());
                            var start_num = $.trim($("input[name='start_num2']").val());
                            var commission = $.trim($("input[name='commission2']").val());

                            if (start_num == '' || start_num < 1) {
                                Alert({msg: '请输入正确的人数', type: 'error'});
                                price_config = new Array();
                                return false;
                            }
                            if (price == '' || price < 0.01) {
                                Alert({msg: '请输入正确的价格', type: 'error'});
                                price_config = new Array();
                                return false;
                            }
                            if (commission < 0) {
                                Alert({msg: '请输入正确的佣金', type: 'error'});
                                return false;
                            }
                            var item = new Array();
                            item['start_num'] = start_num;
                            item['sku_id'] = sku_id;
                            item['price'] = price;
                            item['commission'] = commission;
                            price_config.push(item);
                        }
                    });
                    console.log(price_config);
                    var price_config_len = price_config.length;
                    _this.data.price_config = new Array();
                    if (price_config_len < 1) {
                        Alert({msg: '请输入正确的规则', type: 'error'});
                        return false;
                    }
                    for (var i = 0; i < price_config_len; i++) {
                        var start_num = price_config[i].start_num;
                        var sku_id = price_config[i].sku_id;
                        var price = price_config[i].price;
                        var commission = price_config[i].commission;
                        _this.data.price_config.push(start_num + ',' + price + ',' + commission + ',' + sku_id);
                    }
                }

                _this.data.size = $("input[name='size']").val();
                _this.data.duration = $("input[name='duration']").val();
                _this.data.started_at = $("#started_at").val();
                _this.data.expired_at = $("#expired_at").val();
                _this.data.is_leader_free = $('input[name="is_leader_free"]:checked').val();
                _this.data.leader_limit = $("#leader_limit").val();
                _this.data.member_limit = $("#member_limit").val();
                _this.data.leader_free_size = $("#leader_free_size").val();
                if (_this.data.started_at == '' || _this.data.expired_at == '') {
                    Alert({msg: '时间不能为空', type: 'error'});
                    return false;
                }
                var goods_id = '';
                $(".goods_id").each(function () {
                    if ($(this).val()) {
                        goods_id = $(this).val();
                    }
                });
                if (goods_id == '') {
                    Alert({msg: '请选择要商品', type: 'error'});
                    return false;
                }
                _this.data.goods_id = goods_id;

                if (new Model({
                        url: _global.url.api + 'groupbuy',
                        data: _this.data
                    }).post()) {
                    location.href = '/site/groupbuy';
                }

            });

            //上传图片
            $('body').on('click', '#btn-upload', function (e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
            $('body').on('click', '.item-price-add', function (e) {
                $('.item-price-add').hide();//目前只能增加一个
                $('#size-config').hide().find('[name=size]').val('0');
                $('.item-price-config').append(template('item-price-tpl'));
            });
            $('body').on('click', '.item-price-del', function (e) {
                $('.item-price-add').show();
                $('#size-config').show().find('[name=size]').val('1');
                $(this).parent().parent().remove();
            });
            $('body').on('click', '.item-goods-sku-price-add', function (e) {
                $('.two_config').show();
                $('#size-config').hide().find('[name=size]').val('0');
                $('.item-goods-sku-price-add').hide();
                $('[name="start_num2"]').attr('data-is-del', 0);
            });
            $('body').on('click', '.item-goods-sku-price-del', function (e) {
                $('[name="start_num2"],.price2').val('');
                $('[name="start_num2"]').attr('data-is-del', 1);
                $('.two_config').hide();
                $('#size-config').show().find('[name=size]').val('1');
                $('.item-goods-sku-price-add').show();
            });
            $('body').on('keyup', '.price1,.price2', function (e) {
                var obj = $(this).parents('tr').find('[name=sku_id]');
                if ($(this).val() > 0) {
                    obj.attr('checked', true);
                }
            });
            $("#limited_purchase").click(function (e) {
                if ($(this).is(':checked')) {
                    $(this).parent().children('label').show();
                } else {
                    $(this).parent().children('label').hide();
                }
            });
            $('input[name="is_leader_free"]').click(function (e) {
                if ($(this).val() == 1) {
                    $('.is_leader_free_1').show();
                } else {
                    $('.is_leader_free_1').hide();
                    $('#leader_free_size').val('0');
                }
            });
        },

        change: function (e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        },
        imgPreview: function (img) {
            if (typeof img.id !== 'undefined') {
                this.data.img = img.id;
                $('#img-view').html(template('img-tpl', img));
            }
        },
        select_goods: function (e) {
            this.collection = new Collection({
                container: 'data-list',
                template: 'data-items',
                url: _global.url.api + 'promotion_goods_search',
                condition: {keyword: $("#keyword").val(), is_sku_info: 1, limit: 3},
                model: {
                    event: {
                        '.item-bind:click': 'addgoods',
                        '.show-online:click': 'setshow'
                    },
                    remove: function (e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定删除吗?',
                            ok: function () {
                                if (model.del()) {
                                    _this.collection.reload();
                                }
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    addgoods: function (e) {
                        e.preventDefault();
                        var _this = this;
                        var id = this.data.id;
                        var vals = new Array();
                        $(".goods_id").each(function () {
                            if ($(this).val()) {
                                vals.push($(this).val());
                            }
                        });
                        if (vals.length > 0) {
                            $('.goods-item-del').click();//只能选择一个商品（特别增加代码）
                        }
                        var goods_id = ',' + vals.join(",") + ',';
                        if (goods_id.indexOf(',' + id + ',') != -1) {
                            Alert({msg: '请不要重复添加同一商品', type: 'error'});
                            return false;
                        }
                        $('#goods-item').append(template('goods-item-tpl', {
                            goods_id: this.data.id,
                            goods_name: this.data.name,
                            price: this.data.price
                        }));
                        var goods_sku = this.data.goods_sku;
                        if (goods_sku.length >= 1) {
                            $('.item-price-config').html(template('item-add-goods-sku-price-tpl'));
                            for (var i = 0; i < goods_sku.length; i++) {
                                $('#data-goods-sku-list').append(template('data-goods-sku-items', goods_sku[i]));
                            }
                        } else {
                            $('.item-price-config').html(template('item-add-price-tpl'));
                        }
                        //$("#div_goods").show();
                        $('.goods-item-del').on('click', function (e) {
                            e.preventDefault();
                            $(this).parent().parent().remove();
                            $('.item-bind' + id).html('选择').removeClass('btn-success').addClass('btn-default');
                        });

                        $('.item-bind' + id).html('已选择').removeClass('btn-default').addClass('btn-success');
                    }

                },
                callback: function () {
                    loaded();
                }
            });
            this.collection.fetch();
        }

    };

    new index();

});